package com.elinkway.infinitemovies.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

import com.elinkway.infinitemovies.adapter.SubscriptionListAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.async.RequestSubscriptionMainPageTask;
import com.elinkway.infinitemovies.bean.Subscription;
import com.elinkway.infinitemovies.bean.SubscriptionMainData;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.le123.ysdq.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaopeipei on 2016/9/2.
 */
public class SubScriptionFragment extends BaseFragment {

    public static final String TAG = "subscriptionlist";

    private PublicLoadLayout root;

    private PullToRefreshListView mListView;

    private SubscriptionListAdapter mAdapter;

    private RequestSubscriptionMainPageTask mRequestSubscriptionMainPageTask;

    private List<SubscriptionMainData> mSubscriptionMainDataList;

    private boolean mHasMore = true;

    private int mCurrentPage = 1;

    private int mFirstVisibleItem;

    private int mVisibleItemCount;

    private int mTotalItemCount;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        root = UIs.createPage(getActivity(), R.layout.fragment_subscription);
        root.loading(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mListView = (PullToRefreshListView) root
                .findViewById(R.id.subscription_list);
        resetHasMore();
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 大数据上报
                    LogUtils.e(TAG, "onScrollStateChanged is " + mFirstVisibleItem + " " + mVisibleItemCount
                    + " " + mSubscriptionMainDataList.size() + " " + mTotalItemCount);
                    for (int i = mFirstVisibleItem; i < mFirstVisibleItem + mVisibleItemCount && i<
                            mSubscriptionMainDataList.size(); i++) {
                        if (!mSubscriptionMainDataList.get(i).getIsFirstTimeShowed()) {
                            Map<String, String> dataMap = new HashMap<String, String>();
                            dataMap.put("acode", BigDataConstants.ACODE_EXPOSURE);
                            if (mSubscriptionMainDataList != null
                                    && mSubscriptionMainDataList.get(i).getAlbumList().size() > 0 &&
                                    mSubscriptionMainDataList.get(i).getAlbumList().get(0) != null) {
                                dataMap.put("pid", mSubscriptionMainDataList.get(i).getAlbumList().get(0).getAid());
                            }
                            dataMap.put("ap", BigDataConstants.AD_SUBSCRIPTION_LIST_SHOW);
                            BigDataApi.bigDataCommonReport(dataMap, getActivity());
                            mSubscriptionMainDataList.get(i).setFirstTimeShowed(true);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mFirstVisibleItem = firstVisibleItem;
                mVisibleItemCount = visibleItemCount;
                mTotalItemCount = totalItemCount;
            }
        });
        if (mSubscriptionMainDataList == null) {
            mRequestSubscriptionMainPageTask = new RequestSubscriptionMainPageTask(getActivity(), "cp", "0", "10", false);
            mRequestSubscriptionMainPageTask.setOnListener(new RequestResultListener<Subscription>() {
                @Override
                public boolean onRequestFailed() {
                    return false;
                }

                @Override
                public void onRequestSuccess(int updateId, Subscription result) {
                    if (mAdapter == null) {
                        mAdapter = new SubscriptionListAdapter(getActivity(), result);
                        mListView.setAdapter(mAdapter);
                    } else {
                        if (result.isLoadMore()) {
                            mAdapter.addItemData(result);
                            resetHasMore();
                        } else {
                            mAdapter.setItemData(result);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                    mSubscriptionMainDataList = mAdapter.getItemData().getSubscription();
                    // 专题页头部又添加了一个广告位
                    if (result.getSubscription().size() == MoviesConstant.TOPIC_REQUEST_SIZE) {
                        mCurrentPage += 1;
                    } else {
                        setNoMore();
                    }
                    mListView.onRefreshComplete();
                    root.finish();
                }

                @Override
                public void onPreRequest() {

                }
            });
            mRequestSubscriptionMainPageTask.start();
        }
        return root;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            MoviesApplication.getInstance().setLastPageClassName(TAG);
            if (mSubscriptionMainDataList != null && mSubscriptionMainDataList.size() > 0) {
                for (int i = 0; i < mSubscriptionMainDataList.size(); i++) {
                    mSubscriptionMainDataList.get(i).setFirstTimeShowed(false);
                }
            }
            BigDataApi.bigDataPageShowReport("subscriptionlist", new HashMap<String, String>(), getActivity());
        } else {
        }
    }


    private void resetHasMore() {
        mHasMore = true;
        mListView.setLoadingDrawable(
                getResources().getDrawable(R.drawable.default_ptr_rotate),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListView.setRefreshingLabel(getString(R.string.loading),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListView.setReleaseLabel(getString(R.string.release_loadmore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListView.setPullLabel(getString(R.string.pull_loadmore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
    }

    private void setNoMore() {
        mHasMore = false;
        mListView.setLoadingDrawable(
                getResources().getDrawable(R.drawable.transparent),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListView.setRefreshingLabel(getString(R.string.havenomore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListView.setReleaseLabel(getString(R.string.havenomore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListView.setPullLabel(getString(R.string.havenomore),
                PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
    }

}
